<template>
  <div class="enterpriseManagement">
    <!-- 页面标题 -->
    <div class="pageHeader">
      <h1>企业管理</h1>
    </div>
    
    <!-- 搜索和筛选区域 -->
    <el-card class="searchCard">
      <el-form :inline="true" :model="searchParams" class="demoFormInline">
        <el-form-item label="企业名称">
          <el-input style="width: 200px;" v-model="searchParams.name" placeholder="请输入企业名称" clearable />
        </el-form-item>
        <el-form-item label="联系人姓名">
          <el-input style="width: 200px;" v-model="searchParams.contactName" placeholder="请输入联系人姓名" clearable />
        </el-form-item>
        <el-form-item label="企业地址">
          <el-input style="width: 200px;" v-model="searchParams.address" placeholder="请输入企业地址" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select style="width: 200px;" v-model="searchParams.status" placeholder="请选择状态" clearable>
            <el-option value="" label="全部" />
            <el-option value="0" label="待审核" />
            <el-option value="1" label="正常" />
            <el-option value="2" label="审核失败" />
            <el-option value="3" label="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="openAddDialog" style="margin-left: 10px;">
            <el-icon><Plus /></el-icon>
            新增企业
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据表格 -->
    <el-card>

      
      <el-table :data="enterpriseData" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="企业ID" width="80" />
        <el-table-column prop="name" label="企业名称" min-width="180" />
        <el-table-column prop="contactName" label="联系人" min-width="120" />
        <el-table-column prop="contactPhone" label="联系电话" min-width="120" />
        <el-table-column prop="contactEmail" label="联系邮箱" min-width="180" />
        <el-table-column prop="address" label="企业地址" min-width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getEnterpriseStatusTagType(scope.row.status)">
              {{ getEnterpriseStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作"  fixed="right" width="260">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
            <el-button type="success" size="small" @click="handleAudit(scope.row)" v-if="scope.row.status === '0'">
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="paginationContainer">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[1,10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    

  </div>
  
  <!-- 新增企业对话框 -->
  <el-dialog
    v-model="addDialogVisible"
    title="新增企业"
    width="600px"
    @close="closeAddDialog"
  >
    <el-form
      ref="addFormRef"
      :model="addForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="企业名称" prop="name">
        <el-input v-model="addForm.name" placeholder="请输入企业名称" />
      </el-form-item>
      
      <el-form-item label="企业描述">
        <el-input
          v-model="addForm.description"
          type="textarea"
          placeholder="请输入企业描述（可选）"
          :rows="3"
        />
      </el-form-item>
      
      <el-form-item label="联系人姓名" prop="contactName">
        <el-input v-model="addForm.contactName" placeholder="请输入联系人姓名" />
      </el-form-item>
      
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="addForm.contactPhone" placeholder="请输入联系电话" />
      </el-form-item>
      
      <el-form-item label="联系邮箱" prop="contactEmail">
        <el-input v-model="addForm.contactEmail" placeholder="请输入联系邮箱" />
      </el-form-item>
      
      <el-form-item label="企业地址" prop="address">
        <el-input v-model="addForm.address" placeholder="请输入企业地址" />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeAddDialog">取消</el-button>
        <el-button type="primary" @click="submitAddForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 编辑企业对话框 -->
  <el-dialog
    v-model="editDialogVisible"
    title="编辑企业"
    width="600px"
    @close="closeEditDialog"
  >
    <el-form
      ref="editFormRef"
      :model="editForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="企业名称" prop="name">
        <el-input v-model="editForm.name" placeholder="请输入企业名称" />
      </el-form-item>
      
      <el-form-item label="企业描述">
        <el-input
          v-model="editForm.description"
          type="textarea"
          placeholder="请输入企业描述（可选）"
          :rows="3"
        />
      </el-form-item>
      
      <el-form-item label="联系人姓名" prop="contactName">
        <el-input v-model="editForm.contactName" placeholder="请输入联系人姓名" />
      </el-form-item>
      
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="editForm.contactPhone" placeholder="请输入联系电话" />
      </el-form-item>
      
      <el-form-item label="联系邮箱" prop="contactEmail">
        <el-input v-model="editForm.contactEmail" placeholder="请输入联系邮箱" />
      </el-form-item>
      
      <el-form-item label="企业地址" prop="address">
        <el-input v-model="editForm.address" placeholder="请输入企业地址" />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeEditDialog">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import useEnterpriseManagement from '../hooks/useEnterpriseManagement';

// 使用企业管理hook
const {
  // 状态
  loading,
  // 数据
  enterpriseData,
  pagination,
  searchParams,
  // 方法
  fetchEnterpriseData,
  handleSearch,
  handleReset: resetSearch,
  handleSizeChange,
  handleCurrentChange,
  addEnterprise,
  updateEnterprise,
  deleteEnterprise,
  auditEnterprise,
  getStatusText: getEnterpriseStatusLabel,
  getStatusTagType: getEnterpriseStatusTagType
} = useEnterpriseManagement();

// 新增企业表单数据
const addForm = reactive({
  name: '',
  description: '',
  contactName: '',
  contactPhone: '',
  contactEmail: '',
  address: ''
});

// 编辑企业表单数据
const editForm = reactive({
  id: '',
  name: '',
  description: '',
  contactName: '',
  contactPhone: '',
  contactEmail: '',
  address: ''
});

// 新增企业对话框可见性
const addDialogVisible = ref(false);

// 编辑企业对话框可见性
const editDialogVisible = ref(false);

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入企业名称', trigger: 'blur' },
    { min: 2, max: 100, message: '企业名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  contactName: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' },
    { min: 1, max: 20, message: '联系人姓名长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入联系邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入企业地址', trigger: 'blur' },
    { min: 5, max: 200, message: '企业地址长度在 5 到 200 个字符', trigger: 'blur' }
  ]
};

// 表单引用
const addFormRef = ref();
const editFormRef = ref();

// 打开新增对话框
const openAddDialog = () => {
  // 重置表单
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  // 清空表单数据
  Object.assign(addForm, {
    name: '',
    description: '',
    contactName: '',
    contactPhone: '',
    contactEmail: '',
    address: ''
  });
  // 显示对话框
  addDialogVisible.value = true;
};

// 关闭新增对话框
const closeAddDialog = () => {
  addDialogVisible.value = false;
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
};

// 提交新增企业表单
const submitAddForm = async () => {
  if (!addFormRef.value) return;
  
  try {
    // 表单校验
    await addFormRef.value.validate();
    
    // 提交数据
    await addEnterprise(addForm);
    // 重新获取企业列表
    fetchEnterpriseData();
    // 关闭对话框
    closeAddDialog();
    
  } catch (error) {
    // 表单校验失败或提交失败
    if (error !== false) { // error === false 是表单校验失败的返回值
      console.error('提交表单失败:', error);
    }
  }
};

// 打开编辑对话框
const openEditDialog = (row) => {
  // 填充表单数据
  Object.assign(editForm, {
    id: row.id,
    name: row.name || '',
    description: row.description || '',
    contactName: row.contactName || '',
    contactPhone: row.contactPhone || '',
    contactEmail: row.contactEmail || '',
    address: row.address || ''
  });
  // 显示对话框
  editDialogVisible.value = true;
};

// 关闭编辑对话框
const closeEditDialog = () => {
  editDialogVisible.value = false;
  if (editFormRef.value) {
    editFormRef.value.resetFields();
  }
};

// 提交编辑企业表单
const submitEditForm = async () => {
  if (!editFormRef.value) return;
  
  try {
    // 表单校验
    await editFormRef.value.validate();
    
    // 准备提交数据，移除id字段
    const submitData = {
      name: editForm.name,
      description: editForm.description,
      contactName: editForm.contactName,
      contactPhone: editForm.contactPhone,
      contactEmail: editForm.contactEmail,
      address: editForm.address
    };
    
    // 提交数据
    await updateEnterprise(editForm.id, submitData);
    
    // 显示成功提示
    ElMessage.success('编辑企业成功');
    
    // 重新获取企业列表
    await fetchEnterpriseData();
    
    // 关闭对话框
    closeEditDialog();
    
  } catch (error) {
    // 表单校验失败或提交失败
    if (error !== false) { // error === false 是表单校验失败的返回值
      console.error('提交表单失败:', error);
    }
  }
};

// 编辑企业
const handleEdit = (row) => {
  openEditDialog(row);
};

// 审核企业
const handleAudit = (row) => {
  // 使用确认对话框进行审核操作
  ElMessageBox.confirm('确认审核该企业？', '审核确认', {
    confirmButtonText: '通过',
    cancelButtonText: '拒绝',
    type: 'warning',
    distinguishCancelAndClose: true,
    cancelButtonClass: 'btn-danger'
  }).then(() => {
    // 审核通过
    auditEnterprise(row.id, 1, null)
      .catch(() => {
        // 错误已在hook中处理
      });
  }).catch(action => {
    if (action === 'cancel') {
      // 审核拒绝，需要提供拒绝原因
      ElMessageBox.prompt('请输入拒绝原因', '拒绝审核', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(({ value }) => {
        if (value && value.trim()) {
          auditEnterprise(row.id, 2, value.trim())
            .catch(() => {
              // 错误已在hook中处理
            });
        } else {
          ElMessage.error('请输入拒绝原因');
        }
      }).catch(() => {
        // 取消拒绝
      });
    }
  });
};

// 删除企业
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除企业「${row.name}」？删除后将无法恢复`, '删除确认', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'danger'
  }).then(() => {
    deleteEnterprise(row.id)
      .catch(() => {
        // 错误已在hook中处理
      });
  }).catch(() => {
    // 取消删除
  });
};

// 组件挂载时获取数据
onMounted(() => {
  fetchEnterpriseData();
});
</script>

<style scoped>
.enterpriseManagement {
  padding: 20px;
}

.pageHeader {
  margin-bottom: 20px;
}

.pageHeader h1 {
  font-size: 24px;
  font-weight: 500;
  margin: 0;
}

.searchCard {
  margin-bottom: 20px;
}

/* 不再需要独立的操作按钮区域样式 */
.paginationContainer {
  margin-top: 20px;
  text-align: right;
}

.formHint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}


</style>